<script setup>
import { ref, onMounted, watch } from "vue";
import * as echarts from "echarts";
import { ElTable, ElTableColumn, ElSelect, ElOption, ElButton, ElForm, ElFormItem, ElDatePicker, ElPagination, ElRow, ElCol, ElCard, ElMessage, ElTag } from 'element-plus';
import axios from 'axios';
import { useTokenStore } from '@/stores/token';
import dayjs from 'dayjs';

// 假设这里的 URL 是你的实时视频流地址
const streamUrl = ref("https://intelligent-traffic.oss-cn-beijing.aliyuncs.com/videos/kl.mp4");
const videoKey = ref(Date.now()); // 用于强制重新渲染视频

// 数据和分页相关的变量
const tableData = ref([]);
const warnData = ref([]);
const filteredTableData = ref([]);
const currentPage = ref(1);
const pageSize = ref(10);
const totalItems = ref(0);

// 筛选条件
const filterStartTime = ref(null);
const filterEndTime = ref(null);
const filterLocation = ref("");

// 动态加载的地点选项
const locationOptions = ref([]);

// 定义selectedChart
const selectedChart = ref('traffic-chart');

// 请求表格数据的方法
const fetchTableData = async () => {
    const tokenStore = useTokenStore();
    const token = tokenStore.getToken();

    try {
        const response = await axios.get('/api/flow/listAllFlow', {
            params: {
                pageNumber: currentPage.value,
                pageSize: pageSize.value,
            },
            headers: {
                'Authorization': token
            }
        });

        if (response.data && response.data.code === 0) {
            tableData.value = response.data.data.items.map(item => ({
                currentTime: item.time,
                location: item.spot || 'N/A', // 如果 spot 为空，默认值为 'N/A'
                congestion: item.averageFlow >= 40 ? '高' : item.averageFlow > 20 ? '中' : '低',
                totalTraffic: item.averageFlow * 60,
                oneMinuteTraffic: item.averageFlow,
                oldUrl: item.oldUrl // 添加oldUrl字段
            }));
            totalItems.value = response.data.data.total;
            filteredTableData.value = tableData.value;

            // 更新地点选项
            locationOptions.value = [...new Set(tableData.value.map(item => item.location))];

            drawCharts();
        } else {
            ElMessage.error('Failed to fetch data');
        }
    } catch (error) {
        ElMessage.error('Error occurred while fetching data');
    }
};

// 请求警报数据的方法
const fetchWarnData = async () => {
    const tokenStore = useTokenStore();
    const token = tokenStore.getToken();

    try {
        const response = await axios.get('/api/flow/listAllWarn', {
            params: {
                pageNumber: 1,
                pageSize: 1000,
            },
            headers: {
                'Authorization': token
            }
        });

        if (response.data && response.data.code === 0) {
            warnData.value = response.data.data.items.map(item => ({
                id: item.id,
                vehicleId: item.vehicleId,
                reason: item.reason,
                speed: item.speed,
                time: item.time,
                spot: item.spot || 'N/A',
            }));

            drawCharts();
        } else {
            ElMessage.error('Failed to fetch warn data');
        }
    } catch (error) {
        ElMessage.error('Error occurred while fetching warn data');
    }
};

// 将日期转换为字符串格式的方法
const formatDateTime = (date) => {
    return dayjs(date).format('YYYY-MM-DDTHH:mm:ss');
};

// 筛选数据的方法
const filterData = async () => {
    const params = {};
    if (filterStartTime.value) {
        params.beginTime = formatDateTime(filterStartTime.value);
    }
    if (filterEndTime.value) {
        params.endTime = formatDateTime(filterEndTime.value);
    }
    if (filterLocation.value) {
        params.spot = filterLocation.value;
    }
    const tokenStore = useTokenStore();
    const token = tokenStore.getToken();

    try {
        const response = await axios.get('/api/flow/listFlowByTimeAndSpot', {
            params: {
                ...params,
                pageNumber: currentPage.value,
                pageSize: pageSize.value,
            },
            headers: {
                'Authorization': token
            }
        });

        if (response.data && response.data.code === 0) {
            tableData.value = response.data.data.items.map(item => ({
                currentTime: item.time,
                location: item.spot || 'N/A',
                congestion: item.averageFlow >= 40 ? '高' : item.averageFlow > 20 ? '中' : '低',
                totalTraffic: item.averageFlow * 60,
                oneMinuteTraffic: item.averageFlow,
                oldUrl: item.oldUrl // 添加oldUrl字段
            }));
            totalItems.value = response.data.data.total;
            filteredTableData.value = tableData.value;
            drawCharts();
        } else {
            ElMessage.error('Failed to fetch data');
        }
    } catch (error) {
        ElMessage.error('Error occurred while fetching data');
    }
};

const resetFilters = () => {
    filterStartTime.value = null;
    filterEndTime.value = null;
    filterLocation.value = "";
    fetchTableData();
};

const changeStreamUrl = (url) => {
    console.log('Changing stream URL to:', url); // 调试信息
    streamUrl.value = url;
    videoKey.value = Date.now(); // 更新key以强制重新渲染视频
};

const handleSizeChange = (newSize) => {
    pageSize.value = newSize;
    filterData();
};

const handleCurrentChange = (newPage) => {
    currentPage.value = newPage;
    filterData();
};

// 初始化图表数据的方法
const initChart = (chartId, option) => {
    const chart = echarts.init(document.getElementById(chartId));
    chart.setOption(option);
    chart.resize();
};

// 处理数据并绘制车流量折线图
const drawTrafficChart = () => {
    const locations = [...new Set(filteredTableData.value.map(item => item.location))];
    const series = locations.map(location => {
        return {
            name: location,
            type: 'line',
            data: filteredTableData.value.filter(item => item.location === location).map(item => ({
                value: item.totalTraffic,
                name: item.currentTime
            })),
        };
    });

    const option = {
        title: {
            text: '车流量折线图',
            left: 'center'
        },
        tooltip: {
            trigger: 'axis'
        },
        legend: {
            data: locations,
            top: '10%'
        },
        grid: {
            left: '10%',
            right: '10%',
            top: '20%',
            bottom: '15%'
        },
        xAxis: {
            type: 'category',
            data: filteredTableData.value.map(item => item.currentTime),
        },
        yAxis: {
            type: 'value'
        },
        series: series
    };
    initChart('traffic-chart', option);
};

// 处理数据并绘制违规行为计数折线图
const drawViolationChart = () => {
    const timeIntervals = [];
    const violations = {};

    warnData.value.forEach(item => {
        const timeKey = dayjs(item.time).startOf('15m').format('YYYY-MM-DD HH:mm');
        if (!timeIntervals.includes(timeKey)) {
            timeIntervals.push(timeKey);
        }
        if (!violations[timeKey]) {
            violations[timeKey] = 0;
        }
        violations[timeKey]++;
    });

    const seriesData = timeIntervals.map(time => ({
        value: violations[time] || 0,
        name: time,
    }));

    const option = {
        title: {
            text: '违规行为计数折线图',
            left: 'center'
        },
        tooltip: {
            trigger: 'axis'
        },
        grid: {
            left: '10%',
            right: '10%',
            top: '20%',
            bottom: '15%'
        },
        xAxis: {
            type: 'category',
            data: timeIntervals,
        },
        yAxis: {
            type: 'value'
        },
        series: [{
            name: '违规行为计数',
            type: 'line',
            data: seriesData.map(item => item.value)
        }]
    };
    initChart('violation-chart', option);
};

// 处理数据并绘制各地点违规次数条形图
const drawViolationCountChart = () => {
    const locations = [];
    const violationCounts = {};

    warnData.value.forEach(item => {
        const location = item.spot;
        if (!locations.includes(location)) {
            locations.push(location);
        }
        if (!violationCounts[location]) {
            violationCounts[location] = 0;
        }
        violationCounts[location]++;
    });

    const seriesData = locations.map(location => ({
        value: violationCounts[location] || 0,
        name: location,
    }));

    const option = {
        title: {
            text: '各地点违规次数条形图',
            left: 'center'
        },
        tooltip: {
            trigger: 'axis'
        },
        grid: {
            left: '10%',
            right: '10%',
            top: '20%',
            bottom: '15%'
        },
        xAxis: {
            type: 'category',
            data: locations,
        },
        yAxis: {
            type: 'value'
        },
        series: [{
            name: '违规次数',
            type: 'bar',
            data: seriesData.map(item => item.value)
        }]
    };
    initChart('violation-count-chart', option);
};

// 绘制所有图表
const drawCharts = () => {
    if (selectedChart.value === 'traffic-chart') {
        drawTrafficChart();
    } else if (selectedChart.value === 'violation-chart') {
        drawViolationChart();
    } else if (selectedChart.value === 'violation-count-chart') {
        drawViolationCountChart();
    }
};

onMounted(() => {
    fetchTableData();
    fetchWarnData();
});

watch([currentPage, pageSize], filterData);
watch(selectedChart, () => {
    setTimeout(() => {
        drawCharts();
    }, 300);
});
</script>

<template>
    <el-card class="page-container">
        <template #header>
            <div class="header">
                <span>视频分析</span>
            </div>
        </template>
        <el-row>
            <el-col :span="12">
                <div class="video-container">
                    <video :src="streamUrl" :key="videoKey" autoplay controls loop></video>
                </div>
            </el-col>
            <el-col :span="12">
                <el-form inline>
                    <el-form-item label="切换图表：">
                        <el-select v-model="selectedChart" placeholder="选择图表" style="width: 200px;">
                            <el-option label="车流量折线图" value="traffic-chart"></el-option>
                            <el-option label="违规行为计数折线图" value="violation-chart"></el-option>
                            <el-option label="各地点违规次数条形图" value="violation-count-chart"></el-option>
                        </el-select>
                    </el-form-item>
                </el-form>
                <div v-show="selectedChart === 'traffic-chart'" id="traffic-chart" class="chart-container"></div>
                <div v-show="selectedChart === 'violation-chart'" id="violation-chart" class="chart-container"></div>
                <div v-show="selectedChart === 'violation-count-chart'" id="violation-count-chart" class="chart-container"></div>
            </el-col>
        </el-row>
        <el-row style="margin-top: 20px;">
            <el-col :span="24">
                <el-form inline>
                    <el-form-item label="开始时间：">
                        <el-date-picker
                            v-model="filterStartTime"
                            type="datetime"
                            placeholder="选择开始时间"
                            style="margin-right: 10px; width: 200px;">
                        </el-date-picker>
                    </el-form-item>
                    <el-form-item label="结束时间：">
                        <el-date-picker
                            v-model="filterEndTime"
                            type="datetime"
                            placeholder="选择结束时间"
                            style="margin-right: 10px; width: 200px;">
                        </el-date-picker>
                    </el-form-item>
                    <el-form-item label="筛选地点：">
                        <el-select v-model="filterLocation" placeholder="选择地点" style="margin-right: 10px; width: 200px;">
                            <el-option v-for="location in locationOptions" :key="location" :label="location" :value="location"></el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item>
                        <el-button type="primary" @click="filterData">搜索</el-button>
                        <el-button @click="resetFilters">重置</el-button>
                    </el-form-item>
                </el-form>
            </el-col>
        </el-row>
        <el-row>
            <el-col :span="24">
                <el-table :data="filteredTableData.slice((currentPage - 1) * pageSize, currentPage * pageSize)" style="width: 100%; margin-top: 20px;">
                    <el-table-column prop="currentTime" label="当前时间" />
                    <el-table-column prop="location" label="地点" />
                    <el-table-column label="拥堵情况">
                        <template #default="scope">
                            <el-tag
                                :type="scope.row.congestion === '高' ? 'danger' : scope.row.congestion === '中' ? 'warning' : 'success'">
                                {{ scope.row.congestion }}
                            </el-tag>
                        </template>
                    </el-table-column>
                    <el-table-column prop="totalTraffic" label="总车流量" />
                    <el-table-column prop="oneMinuteTraffic" label="1分钟车流量" />
                    <el-table-column label="操作">
                        <template #default="scope">
                            <el-button type="primary" @click="changeStreamUrl(scope.row.oldUrl)">切换视频</el-button>
                        </template>
                    </el-table-column>
                </el-table>
                <el-row style="margin-top: 20px;" justify="end">
                    <el-col :span="24">
                        <el-pagination
                            background
                            :total="totalItems"
                            :page-size="pageSize"
                            :current-page="currentPage"
                            :page-sizes="[10, 20, 30, 40]"
                            layout="total, sizes, prev, pager, next, jumper"
                            @size-change="handleSizeChange"
                            @current-change="handleCurrentChange"
                            style="margin-top: 20px; margin-right: 60px; justify-content: flex-end">
                        </el-pagination>
                    </el-col>
                </el-row>
            </el-col>
        </el-row>
    </el-card>
</template>

<style lang="scss" scoped>
.page-container {
    min-height: 100%;
    box-sizing: border-box;

    .header {
        display: flex;
        align-items: center;
        justify-content: space-between;
    }

    .video-container {
        margin-top: 100px;
        margin-right: 30px;
        video {
            width: 100%;
            height: auto;
        }
    }

    .chart-container {
        width: 100%;
        height: 400px;
        margin-top: 20px;
    }
}
</style>
